package com.example.medicinebox.data

import com.example.medicinebox.network.MbApiService
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

interface MbRepository {
    suspend fun subscribeDevice(targetID: String, resultHandler: (String) -> Unit)

    /* 返回是否推送成功 */
    suspend fun publishControlMessage(message: String)

    fun setDefaultHandler(messageHandler: (String) -> Unit)

    /* 尝试重启 Repo */
    fun restartRepository()
}

class NetworkMbRepository(
    private val mbApiService: MbApiService
): MbRepository {
    private val messageHandler: (String) -> Unit = {}
    private val deviceID: String = "my-phone-1617f7da-8427-4e6e-aa00-ada4a3eb4ea2"

    init {
        initRepository()
    }

    private fun initRepository() {
        /* 先注册APP设备到服务器 */
        CoroutineScope(Dispatchers.IO).launch {
            mbApiService.sendMessages(
                "zncdz,devType=MP,msgType=REG,devID=%s,t=00:00,m=0,d=0,a=0,u=0,v=0,x=0,y=0"
                    .format(deviceID)
            )
        }
    }


    override suspend fun subscribeDevice(targetID: String, resultHandler: (String) -> Unit) {
        mbApiService.setMessageHandler(resultHandler)
        mbApiService.sendMessages(
            "zncdz,devType=MP,msgType=SUB,devID=%s,tgtID=%s"
                .format(deviceID, targetID)
        )
    }

    override suspend fun publishControlMessage(message: String) {
        if (!mbApiService.isConnectedSuccess) {
            messageHandler("ErrorNetwork")
            return
        }
        mbApiService.sendMessages(
            "zncdz,devType=MP,msgType=PUB,devID=%s,%s"
                .format(deviceID, message)
        )
    }

    override fun setDefaultHandler(messageHandler: (String) -> Unit) {
        mbApiService.setMessageHandler(messageHandler)
    }

    override fun restartRepository() {
        mbApiService.restartService()
        initRepository()
    }

}
